package dp.multi;

import java.util.Arrays;

public class Solution_718 {

    int[][] memo;

    public int findLength(int[] nums1, int[] nums2) {
        int m = nums1.length;
        int n = nums2.length;
        memo = new int[m][n];
        for (int i = 0; i < m; i++) {
            Arrays.fill(memo[i], -1);
        }
        int res = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                res = Math.max(res, dfs(i, j, nums1, nums2));
            }
        }
        return res;
    }

    private int dfs(int i, int j, int[] nums1, int[] nums2) {
        if (i < 0 || j < 0)
            return 0;
        if (memo[i][j] != -1)
            return memo[i][j];
        if (nums1[i] == nums2[j])
            return memo[i][j] = dfs(i - 1, j - 1, nums1, nums2) + 1;
        return memo[i][j] = 0;
    }
}
